<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>VIP自动续费管理</span>
      </div>
      
      <!-- 用户VIP状态 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="24">
          <el-alert
            v-if="userVipInfo.isVip"
            title="您当前是VIP用户"
            type="success"
            :description="`VIP到期时间：${userVipInfo.expireTime}`"
            show-icon
            :closable="false">
          </el-alert>
          <el-alert
            v-else
            title="您当前不是VIP用户"
            type="info"
            description="购买VIP享受更多特权服务"
            show-icon
            :closable="false">
          </el-alert>
        </el-col>
      </el-row>

      <!-- 自动续费状态 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="24">
          <el-card shadow="never" style="border: 1px solid #e4e7ed;">
            <div slot="header">
              <span>自动续费状态</span>
            </div>
            
            <div v-if="autoRenewInfo.hasAutoRenew">
              <el-row :gutter="20">
                <el-col :span="12">
                  <div class="status-item">
                    <span class="label">自动续费：</span>
                    <el-tag type="success">已开启</el-tag>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="status-item">
                    <span class="label">下次续费时间：</span>
                    <span>{{ autoRenewInfo.nextRenewTime }}</span>
                  </div>
                </el-col>
              </el-row>
              
              <el-row :gutter="20" style="margin-top: 15px;">
                <el-col :span="12">
                  <div class="status-item">
                    <span class="label">续费金额：</span>
                    <span class="amount">¥{{ autoRenewInfo.amount }}</span>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="status-item">
                    <span class="label">续费天数：</span>
                    <span>{{ autoRenewInfo.vipDays }}天</span>
                  </div>
                </el-col>
              </el-row>
            </div>
            
            <div v-else>
              <el-empty description="您还未开启自动续费">
                <el-button type="primary" @click="goToBuyVip">去购买VIP</el-button>
              </el-empty>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 微信委托代扣签约状态 -->
      <el-row :gutter="20" v-if="autoRenewInfo.hasAutoRenew">
        <el-col :span="24">
          <el-card shadow="never" style="border: 1px solid #e4e7ed;">
            <div slot="header">
              <span>微信委托代扣签约</span>
              <el-tooltip content="签约后系统将自动从您的微信账户扣费续费VIP" placement="top">
                <i class="el-icon-question" style="margin-left: 5px; color: #909399;"></i>
              </el-tooltip>
            </div>
            
            <div class="contract-status">
              <el-row :gutter="20">
                <el-col :span="12">
                  <div class="status-item">
                    <span class="label">签约状态：</span>
                    <el-tag 
                      :type="getContractStatusType(contractInfo.contractStatus)"
                      :icon="getContractStatusIcon(contractInfo.contractStatus)">
                      {{ contractInfo.statusText }}
                    </el-tag>
                  </div>
                </el-col>
                <el-col :span="12" v-if="contractInfo.contractTime">
                  <div class="status-item">
                    <span class="label">签约时间：</span>
                    <span>{{ contractInfo.contractTime }}</span>
                  </div>
                </el-col>
              </el-row>
              
              <el-row :gutter="20" style="margin-top: 15px;" v-if="contractInfo.contractId">
                <el-col :span="24">
                  <div class="status-item">
                    <span class="label">合约编号：</span>
                    <span class="contract-id">{{ contractInfo.contractId }}</span>
                  </div>
                </el-col>
              </el-row>
              
              <!-- 操作按钮 -->
              <div class="contract-actions" style="margin-top: 20px;">
                <el-button 
                  v-if="contractInfo.contractStatus === null || contractInfo.contractStatus === 0"
                  type="primary" 
                  :loading="signing"
                  @click="handleSign">
                  <i class="el-icon-edit-outline"></i>
                  {{ contractInfo.contractStatus === 0 ? '重新签约' : '立即签约' }}
                </el-button>
                
                <el-button 
                  v-if="contractInfo.contractStatus === 1"
                  type="success" 
                  disabled>
                  <i class="el-icon-check"></i>
                  已完成签约
                </el-button>
                
                <el-button 
                  type="info" 
                  @click="refreshContractStatus">
                  <i class="el-icon-refresh"></i>
                  刷新状态
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 操作按钮 -->
      <el-row :gutter="20" style="margin-top: 20px;" v-if="autoRenewInfo.hasAutoRenew">
        <el-col :span="24">
          <el-button 
            type="danger" 
            plain
            @click="handleCancelAutoRenew">
            <i class="el-icon-close"></i>
            取消自动续费
          </el-button>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import { getWechatContractStatus, signWechatContract, cancelAutoRenew } from '@/api/vip/autoRenew'
import { getUserVipStatus } from '@/api/vip/vipPayment'

export default {
  name: "VipAutoRenew",
  data() {
    return {
      // 用户VIP信息
      userVipInfo: {
        isVip: false,
        expireTime: null
      },
      // 自动续费信息
      autoRenewInfo: {
        hasAutoRenew: false,
        nextRenewTime: null,
        amount: 0,
        vipDays: 0
      },
      // 签约信息
      contractInfo: {
        hasContract: false,
        contractStatus: null,
        contractId: null,
        contractCode: null,
        contractTime: null,
        statusText: '未知'
      },
      // 签约中状态
      signing: false
    }
  },
  created() {
    this.loadUserInfo()
  },
  methods: {
    // 加载用户信息
    async loadUserInfo() {
      try {
        // 这里需要获取当前登录用户的ID
        const userId = this.$store.getters.userId || 1 // 临时使用1，实际应该从store获取
        
        // 获取VIP状态
        const vipResponse = await getUserVipStatus(userId)
        if (vipResponse.code === 200) {
          this.userVipInfo = vipResponse.data || {}
        }
        
        // 获取签约状态
        await this.loadContractStatus(userId)
      } catch (error) {
        console.error('加载用户信息失败:', error)
        this.$modal.msgError('加载用户信息失败')
      }
    },
    
    // 加载签约状态
    async loadContractStatus(userId) {
      try {
        const response = await getWechatContractStatus(userId)
        if (response.code === 200) {
          this.contractInfo = response.data || {}
          // 如果有签约信息，说明有自动续费
          if (response.data) {
            this.autoRenewInfo.hasAutoRenew = true
            // 这里可以从响应中获取更多自动续费信息
          }
        }
      } catch (error) {
        console.error('加载签约状态失败:', error)
      }
    },
    
    // 处理签约
    async handleSign() {
      try {
        this.signing = true
        const userId = this.$store.getters.userId || 1
        
        const response = await signWechatContract(userId)
        if (response.code === 200) {
          this.$modal.msgSuccess('签约成功！')
          // 刷新签约状态
          await this.loadContractStatus(userId)
        } else {
          this.$modal.msgError(response.msg || '签约失败')
        }
      } catch (error) {
        console.error('签约失败:', error)
        this.$modal.msgError('签约失败：' + error.message)
      } finally {
        this.signing = false
      }
    },
    
    // 刷新签约状态
    async refreshContractStatus() {
      const userId = this.$store.getters.userId || 1
      await this.loadContractStatus(userId)
      this.$modal.msgSuccess('状态已刷新')
    },
    
    // 取消自动续费
    async handleCancelAutoRenew() {
      try {
        await this.$modal.confirm('确定要取消自动续费吗？取消后将不会自动续费VIP。')
        
        const userId = this.$store.getters.userId || 1
        const response = await cancelAutoRenew(userId)
        
        if (response.code === 200) {
          this.$modal.msgSuccess('已取消自动续费')
          // 重新加载信息
          await this.loadUserInfo()
        } else {
          this.$modal.msgError(response.msg || '取消失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('取消自动续费失败:', error)
          this.$modal.msgError('取消失败：' + error.message)
        }
      }
    },
    
    // 去购买VIP
    goToBuyVip() {
      // 跳转到VIP购买页面
      this.$router.push('/vip/purchase')
    },
    
    // 获取签约状态类型
    getContractStatusType(status) {
      if (status === null) return 'warning'
      if (status === 1) return 'success'
      if (status === 0) return 'danger'
      return 'info'
    },
    
    // 获取签约状态图标
    getContractStatusIcon(status) {
      if (status === null) return 'el-icon-warning'
      if (status === 1) return 'el-icon-check'
      if (status === 0) return 'el-icon-close'
      return 'el-icon-question'
    }
  }
}
</script>

<style scoped>
.status-item {
  margin-bottom: 10px;
}

.status-item .label {
  font-weight: bold;
  color: #606266;
  margin-right: 8px;
}

.amount {
  color: #E6A23C;
  font-weight: bold;
  font-size: 16px;
}

.contract-id {
  font-family: monospace;
  background-color: #f5f7fa;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 12px;
}

.contract-status {
  padding: 10px 0;
}

.contract-actions {
  border-top: 1px solid #ebeef5;
  padding-top: 15px;
}

.box-card {
  margin-bottom: 20px;
}
</style>